<?php
class DBUtil{
	
	/**
	 * 计算某个表的行数
	 */
	public static function count($tblName,$condition = ''){
		$sql = 'select count(*) from '.$tblName;
		if($condition === ''){
			$sql .= ' limit 1';
		} else {
			$sql .= ' where '.$condition.' limit 1';
		}
		$ret = Yii::app()->db->createCommand($sql)->queryScalar();
		return intval($ret);
	}
	
    /**
	 * 针对某个表中某个属性，进行加1操作
	 */
	public static function increProp($tblName,$prop,$condition = '',$delta = 1){
		$sql = 'update '.$tblName.' set '.$prop.'='.$prop.'+'.$delta.' ';
		if($condition !== ''){
			$sql .= ' where '.$condition;
		}
		self::exec($sql);	
	}

    /**
	 * 针对某个表中某个属性，进行减1操作
	 */
	public static function decreProp($tblName,$prop,$condition = '',$delta = 1){
		$sql = 'update '.$tblName.' set '.$prop.'='.$prop.'-'.$delta.' ';
		if($condition !== ''){
			$sql .= ' where '.$condition;
		}
		self::exec($sql);	
	}
	
	/**
	 * 插入一条记录
	 */
	public static function insert($tblName,$props = array()){
		//insert into tbl_user(id,name) values(1,'xxx');
		$sql = 'insert into '.$tblName.'(';
		$valuesSql = 'values(';
		foreach($props as $field=>$val){
			$sql .= $field.',';
			$valuesSql .= "'$val',";
		}
		$sql = rtrim($sql,',');
		$sql .= ') ';
		$valuesSql = rtrim($valuesSql,',');
		$valuesSql .=')';
		$sql .= $valuesSql;
		self::exec($sql);
	}
	
	public static function buildWhere($condition = array()){
		if(empty($condition)){
			return ' ';
		} else {
			$size = count($condition);
			if($size === 1){
				return " where ".$condition[0]." ";
			} else {
				$where = " where ".$condition[0]." ";
				for($i = 1; $i < $size; $i++){
					$where .= " and ".$condition[$i]." ";
				}
				return $where;
			}
		}
	}
	
	public static function buildFrom($tblName){
		return ' from '.$tblName.' ';
	}
	
	public static function exec($sql){
		Yii::app()->db->createCommand($sql)->execute();
	}	
	
	public static function cmd($sql){
		return Yii::app()->db->createCommand($sql);
	}
	
	public static function queryAll($sql){
		return Yii::app()->db->createCommand($sql)->queryAll();
	}
	
	public static function queryScalar($sql){
		return Yii::app()->db->createCommand($sql)->queryScalar();
	}
	
	public static function queryColumn($sql){
		return Yii::app()->db->createCommand($sql)->queryColumn();
	}
	
	public static function queryRow($sql){
		return Yii::app()->db->createCommand($sql)->queryRow();
	}
}
